﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using Entity;

namespace SalesVMT
{
    public partial class frmIncome : Form
    {
        DialogResult dlgResult;
        IncomeInfo Incomeinf;
        public frmIncome(int _Income_ID)
        {
            InitializeComponent();
            Incomeinf = new IncomeInfo();
            lblNo.Text = UISetting.AutoFillIncomeCode();
            mtxIncomeDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            txtReceive.Text = UsersDB.GetInfoByUsersName(Program.strUserName).Users_FullName;
            DisplayFrame();

            UISetting.LoadCustomerFromShipment(ref cboCustomer);
            Incomeinf.Income_ID = _Income_ID;
            if (_Income_ID > 0)
            {
                Incomeinf = IncomeDB.GetInfo(_Income_ID);
                InfoToForm();
                LoadListByIncome();
                UISetting.LoadCustomerFromShipment1(ref cboCustomer);
                LockForm(false);
                btnSave.Enabled = false;
            }
           
            this.KeyPreview = true;
            dlgResult = DialogResult.Cancel;
            
        }
        private void DisplayFrame()
        {
            UISetting.AddColumn(ref dgvList1, "Shipment_ID", "Khóa", "", 1, false, true);
            UISetting.AddColumn(ref dgvList1, "RowNumber", "STT", "C", 35, true, true);
            UISetting.AddColumn(ref dgvList1, "Shipment_Code", "Phiếu NK", "", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Shipment_Date", "Ngày nhập", "C", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Shipment_DebitDays", "Số ngày nợ", "R", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Shipment_Total", "Tổng cộng", "R", 95, true, true);
            UISetting.AddColumn(ref dgvList1, "Shipment_Pay", "Đã thu", "R", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Remainder", "Còn thu", "R", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Instalment", "Thu kỳ này", "R", 100, true, false);
        }
        private void FormToInfo()
        {
            Incomeinf.Income_Code = lblNo.Text;
            Incomeinf.Income_Date = DateTime.ParseExact(mtxIncomeDate.Text, "dd/MM/yyyy", null);
            Incomeinf.Income_CustomerID = Convert.ToInt32(cboCustomer.SelectedValue);
            Incomeinf.Income_Receive = txtReceive.Text;
            Incomeinf.Income_Reason = txtReason.Text;
            Incomeinf.Income_Total = Convert.ToDecimal(txtTotal.Text);
            Incomeinf.Income_UsersID = UsersDB.GetInfoByUsersName(Program.strUserName).Users_ID;
        }
        private void InfoToForm()
        {
            lblNo.Text = Incomeinf.Income_Code;
            mtxIncomeDate.Text = Convert.ToDateTime(Incomeinf.Income_Date).ToString("dd/MM/yyyy");
            cboCustomer.SelectedValue = Incomeinf.Income_CustomerID;
            txtReceive.Text = Incomeinf.Income_Receive;
            txtReason.Text = Incomeinf.Income_Reason;
            txtTotal.Text = Convert.ToDecimal(Incomeinf.Income_Total).ToString("#,##0");
        }

        private void LoadListByCustomer()
        {
            dgvList1.Rows.Clear();
            DataTable _dt = new DataTable();
            _dt = ShipmentDB.GetAllByCustomerForIncome(Convert.ToInt32(cboCustomer.SelectedValue)).Tables[0];
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList1.Rows.Insert(i, 1);
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList1.Rows[i].Cells["Shipment_ID"].Value = _dt.Rows[i]["Shipment_ID"].ToString();
                dgvList1.Rows[i].Cells["Shipment_Code"].Value = _dt.Rows[i]["Shipment_Code"].ToString();
                dgvList1.Rows[i].Cells["Shipment_Date"].Value = Convert.ToDateTime(_dt.Rows[i]["Shipment_Date"]).ToString("dd/MM/yyyy");
                dgvList1.Rows[i].Cells["Shipment_DebitDays"].Value = _dt.Rows[i]["Shipment_DebitDays"].ToString();
                dgvList1.Rows[i].Cells["Shipment_Total"].Value = Convert.ToDecimal(_dt.Rows[i]["Shipment_Total"]).ToString("#,##0");
                dgvList1.Rows[i].Cells["Shipment_Pay"].Value = Convert.ToDecimal(_dt.Rows[i]["Shipment_Pay"]).ToString("#,##0");
                dgvList1.Rows[i].Cells["Remainder"].Value = Convert.ToDecimal(Convert.ToDecimal(_dt.Rows[i]["Shipment_Total"]) - Convert.ToDecimal(_dt.Rows[i]["Shipment_Pay"])).ToString("#,##0");
                dgvList1.Rows[i].Cells["Instalment"].Value = 0;

            }
            
        }
        private void LoadListByIncome()
        {
            dgvList1.Rows.Clear();
            DataTable _dt = new DataTable();
            _dt = IncomeDetailsDB.GetAllByIncome(Incomeinf.Income_ID).Tables[0];
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList1.Rows.Insert(i, 1);
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList1.Rows[i].Cells["Shipment_ID"].Value = _dt.Rows[i]["Shipment_ID"].ToString();
                dgvList1.Rows[i].Cells["Shipment_Code"].Value = _dt.Rows[i]["Shipment_Code"].ToString();
                dgvList1.Rows[i].Cells["Shipment_Date"].Value = Convert.ToDateTime(_dt.Rows[i]["Shipment_Date"]).ToString("dd/MM/yyyy");
                dgvList1.Rows[i].Cells["Shipment_DebitDays"].Value = _dt.Rows[i]["IncomeDetails_DebitDays"].ToString();
                dgvList1.Rows[i].Cells["Shipment_Total"].Value = Convert.ToDecimal(_dt.Rows[i]["Shipment_Total"]).ToString("#,##0");
                dgvList1.Rows[i].Cells["Shipment_Pay"].Value = Convert.ToDecimal(_dt.Rows[i]["IncomeDetails_Pay"]).ToString("#,##0");
                dgvList1.Rows[i].Cells["Remainder"].Value = Convert.ToDecimal(Convert.ToDecimal(_dt.Rows[i]["Shipment_Total"]) - Convert.ToDecimal(_dt.Rows[i]["IncomeDetails_Pay"])).ToString("#,##0");
                dgvList1.Rows[i].Cells["Instalment"].Value = Convert.ToDecimal(_dt.Rows[i]["IncomeDetails_Instalment"]).ToString("#,##0");
            }

        }

        private IncomeDetailsInfo[] ReadIncomeDetails()
        {
            int n = dgvList1.Rows.Count;
            if (n > 0)
            {
                IncomeDetailsInfo[] tracks = new IncomeDetailsInfo[n];
                for (int i = 0; i < n; i++)
                {
                    tracks[i] = new IncomeDetailsInfo();
                    tracks[i].IncomeDetails_ShipmentID = Convert.ToInt32(dgvList1.Rows[i].Cells["Shipment_ID"].Value);
                    tracks[i].IncomeDetails_DebitDays = Convert.ToInt32(dgvList1.Rows[i].Cells["Shipment_DebitDays"].Value);
                    tracks[i].IncomeDetails_Pay = Convert.ToDecimal(dgvList1.Rows[i].Cells["Shipment_Pay"].Value);
                    tracks[i].IncomeDetails_Instalment = Convert.ToDecimal(dgvList1.Rows[i].Cells["Instalment"].Value);
                }
                return tracks;
            }
            else
            {
                return null;
            }
        }
        private bool CheckValid()
        {
            decimal dec;
            if (!Decimal.TryParse(txtTotal.Text, out dec)||dec == 0)
            {
                MessageBox.Show("Chưa có mặt hàng nào được trả kỳ này! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }
        private void LockForm(bool Lock)
        {
            cboCustomer.Visible = Lock;
            lblCustomer.Visible = !Lock;
            dgvList1.Columns["Instalment"].ReadOnly = !Lock;
        }

        private void TotalRowsPrice()
        {
            decimal Total = 0;
            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                Total += Convert.ToDecimal(dgvList1.Rows[i].Cells["Instalment"].Value);
            }
            txtTotal.Text = Total.ToString("#,##0");
        }

        private void dgvList1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            decimal newDecimal;
            decimal Shipment_Total = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Shipment_Total"].Value);
            decimal Shipment_Pay = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Shipment_Pay"].Value);

            if (e.ColumnIndex == dgvList1.Columns["Instalment"].Index)
            {

                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    MessageBox.Show("Đơn giá phải là số dương", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (newDecimal > Shipment_Total - Shipment_Pay)
                {
                    e.Cancel = true;
                    MessageBox.Show("Số lượng không được vượt giá trị ''Còn lại''", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
          
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValid())
                return;
            FormToInfo();
            IncomeDetailsInfo[] tracks = ReadIncomeDetails();
            if (tracks == null)
            {
                MessageBox.Show("Chưa có mặt hàng nào được nhập! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
                Incomeinf.Income_ID = IncomeDB.Insert(Incomeinf);
                if (Incomeinf.Income_ID > 0)
                {
                    LockForm(false);
                    for (int i = 0; i < tracks.Length; i++)
                    {
                        tracks[i].IncomeDetails_IncomeID = Incomeinf.Income_ID;
                        if (IncomeDetailsDB.Insert(tracks[i]) > 0)
                        {
                            Program.taskbarNotifier.Show(Message.Info, Message.Create_Complete, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                            dlgResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show(Message.Create_Error, Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            dlgResult = DialogResult.Cancel;
                        }
                    }
                }
                else
                {
                    MessageBox.Show(Message.Create_Error, Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dlgResult = DialogResult.Cancel;
                }

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (Incomeinf.Income_ID == 0)
            {
                MessageBox.Show("Cần phải lưu dữ liệu trước khi in! Hãy nhập lại.", Message.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
                frmReport f = new frmReport("PHIEU THU", new string[] { Incomeinf.Income_ID.ToString(), "Phiếu thu"});
                f.Show();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            
            this.Close();
        }

        private void frmIncome_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Incomeinf.Income_ID = 0;
            lblNo.Text = UISetting.AutoFillIncomeCode();
            mtxIncomeDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            if(cboCustomer.Text !="")
            cboCustomer.SelectedIndex = 0;
            LoadListByCustomer();
            txtReceive.Text = UsersDB.GetInfoByUsersName(Program.strUserName).Users_FullName;
            txtTotal.Text = "0.0";
            LockForm(true);
        }

        private void frmIncome_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control && !dgvList1.Focused)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.F3:
                    if(Incomeinf.Income_ID==0)
                    btnSave_Click(null, null);
                    break;
                case Keys.F7:
                    btnPrint_Click(null, null);
                    break;
                case Keys.Escape:
                    
                    this.DialogResult = dlgResult;
                    this.Close();
                    break;
            }
        }

        private void cboCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            lblCustomer.Text = cboCustomer.Text;
            if (Incomeinf.Income_ID > 0)
                LoadListByIncome();
            else
                LoadListByCustomer();
        }

        private void dgvList1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvList1.Columns["Instalment"].Index)
            {
                decimal d = decimal.Parse(e.Value.ToString());
                e.Value = d.ToString("#,##0");
            }
        }

        private void dgvList1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            decimal Instalment;
            Instalment = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Instalment"].Value);
            dgvList1.Rows[e.RowIndex].Cells["Instalment"].Value = Instalment.ToString("#,##0");
            TotalRowsPrice();
        }
    }
}